<template>
  <div class="app-container">
    <!-- 状态导航栏 -->
    <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
      <el-tab-pane label="全部" name=""></el-tab-pane>
      <el-tab-pane label="审核中" name="1"></el-tab-pane>
      <el-tab-pane label="治疗中" name="2"></el-tab-pane>
      <el-tab-pane label="已完成" name="3"></el-tab-pane>
      <el-tab-pane label="已失败" name="4"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主键id" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入主键id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="患者id" prop="patientsId">
        <el-input v-model="queryParams.patientsId" placeholder="请输入患者id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="医护人员" prop="employeeId">
        <el-select v-model="queryParams.employeeId" placeholder="请选择医护人员" clearable>
          <el-option v-for="dict in employeeOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="处方开据时间" prop="createTime" label-width="100px">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择处方开据时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态,1 审核中，2 治疗中，3 已完成，4 已失败" clearable>
          <el-option v-for="dict in sys_prescription_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="实收金额" prop="money">
        <el-input v-model="queryParams.money" placeholder="请输入实收金额" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['prescription:prescription:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['prescription:prescription:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['prescription:prescription:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['prescription:prescription:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Bell" :disabled="single" @click="handleRemind"
          v-hasPermi="['prescription:prescription:remind']">提醒用药</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prescriptionList" @selection-change="handleSelectionChange"
      @row-dblclick="handleView">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="患者id" align="center" prop="patientsId" />
      <el-table-column label="医护人员id" align="center" prop="employeeId" />
      <el-table-column label="处方开据时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_prescription_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="实收金额" align="center" prop="money" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template #default="scope">
          <el-button v-if="scope.row.status === '1'" link type="primary" icon="Check"
            @click="handleStatusUpdate(scope.row)" v-hasPermi="['prescription:prescription:change']">审核通过</el-button>
          <el-button v-if="scope.row.status === '2'" link type="primary" icon="Check"
            @click="handleStatusUpdate(scope.row)" v-hasPermi="['prescription:prescription:change']">治疗完成</el-button>
          <el-button v-if="scope.row.status !== '3' && scope.row.status !== '4'" link type="danger" icon="CircleClose"
            @click="handleSetFailed(scope.row)" v-hasPermi="['prescription:prescription:change']">取消处方</el-button>
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['prescription:prescription:edit']"
          >修改</el-button> -->
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['prescription:prescription:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改处方对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="prescriptionRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者id" prop="patientsId">
              <el-input v-model="form.patientsId" placeholder="请输入患者id" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="医护人员id" prop="employeeId">
              <el-input v-model="form.employeeId" placeholder="请输入医护人员id" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实收金额" prop="money">
              <el-input v-model="form.money" placeholder="请输入实收金额" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">处方明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddPrescriptionDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeletePrescriptionDetail">删除</el-button>
          </el-col>
        </el-row>

        <el-table :data="prescriptionDetailList" :row-class-name="rowPrescriptionDetailIndex"
          @selection-change="handlePrescriptionDetailSelectionChange" ref="prescriptionDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="药品选择" prop="medicationId" min-width="400">
            <template #default="scope">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-select v-model="scope.row.categoryFilter" placeholder="选择药品类别" clearable
                    @change="(value) => handleCategoryChange(value, scope.$index)">
                    <el-option v-for="category in categoryOptions" :key="category" :label="category" :value="category">
                      <span>{{ category }}</span>
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select v-model="scope.row.dosageFormFilter" placeholder="选择剂型" clearable
                    @change="(value) => handleDosageFormChange(value, scope.$index)">
                    <el-option v-for="form in dosageFormOptions" :key="form" :label="form" :value="form">
                      <span>{{ form }}</span>
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select v-model="scope.row.medicationId" placeholder="选择药品" filterable clearable
                    @change="(value) => handleMedicationChange(value, scope.$index)">
                    <el-option v-for="item in getFilteredMedications(scope.$index)" :key="item.id" :label="item.name"
                      :value="item.id">
                      <div class="medication-option">
                        <div class="medication-info">
                          <span class="medication-name">{{ item.name }}</span>
                          <div class="medication-meta">
                            <span class="medication-code">编码：{{ item.code }}</span>
                            <span class="medication-type">剂型：{{ item.dosageFormText }}</span>
                            <span class="medication-category">类别：{{ item.categoryText }}</span>
                          </div>
                        </div>
                        <div class="medication-details">
                          <span class="stock" :class="{ 'low-stock': item.stock < 10 }">
                            库存: {{ item.stock }}
                          </span>
                          <span class="price">￥{{ item.price }}</span>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="用药剂量" prop="dosage" width="200">
            <template #default="scope">
              <span>{{ scope.row.dosage }}</span>
              <!-- <el-input
                v-model="scope.row.dosage"
                placeholder="请输入用药剂量"
                type="textarea"
                :rows="2"
                :maxlength="100"
                show-word-limit
              /> -->
            </template>
          </el-table-column>
          <el-table-column label="药品总量" prop="quantity" width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" placeholder="请输入药品总量" :min="1"
                :max="scope.row.stockQuantity || 999999" @change="(value) => calculateTotal(scope.$index)" />
              <div class="stock-info" v-if="scope.row.stockQuantity">
                <span :class="{ 'stock-warning': scope.row.stockQuantity < 10 }">
                  库存: {{ scope.row.stockQuantity }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="120">
            <template #default="scope">
              <span>￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总价" prop="totalAmount" width="120">
            <template #default="scope">
              <span>￥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看处方详细对话框 -->
    <el-dialog title="处方详细信息" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="主键id">{{
          viewForm.id
          }}</el-descriptions-item>
        <el-descriptions-item label="患者id">{{
          viewForm.patientsId
          }}</el-descriptions-item>
        <el-descriptions-item label="医护人员id">{{
          viewForm.employeeId
          }}</el-descriptions-item>
        <el-descriptions-item label="处方开据时间">{{
          parseTime(viewForm.createTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="sys_prescription_status" :value="viewForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="实收金额">{{
          viewForm.money
          }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">处方明细信息</el-divider>
      <el-table :data="viewForm.prescriptionDetailList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品id" prop="medicationId" align="center" />
        <el-table-column label="用药剂量" prop="dosage" align="center" />
        <el-table-column label="药品总量" prop="quantity" align="center" />
        <el-table-column label="药品单价" prop="price" align="center" />
      </el-table>
    </el-dialog>

    <!-- 状态修改对话框 -->
    <el-dialog :title="statusForm.status === '1' ? '处方审核' : '处方治疗完成确认'" v-model="statusOpen" width="500px"
      append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="处方ID">{{ statusForm.id }}</el-descriptions-item>
        <el-descriptions-item label="患者ID">{{ statusForm.patientsId }}</el-descriptions-item>
        <el-descriptions-item label="医护人员ID">{{ statusForm.employeeId }}</el-descriptions-item>
        <el-descriptions-item label="处方开据时间">{{ parseTime(statusForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <dict-tag :options="sys_prescription_status" :value="statusForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="下一状态">
          <dict-tag :options="sys_prescription_status" :value="getNextStatus(statusForm.status)" />
        </el-descriptions-item>
        <el-descriptions-item label="实收金额">{{ statusForm.money }}</el-descriptions-item>
      </el-descriptions>
      <div class="dialog-footer" style="margin-top: 20px;">
        <el-button type="primary" @click="confirmStatusChange">{{ statusForm.status === '1' ? '确认审核通过' : '确认完成治疗'
          }}</el-button>
        <el-button @click="statusOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置失败状态确认对话框 -->
    <el-dialog title="设置处方失败状态确认" v-model="failureOpen" width="500px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="处方ID">{{ statusForm.id }}</el-descriptions-item>
        <el-descriptions-item label="患者ID">{{ statusForm.patientsId }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <dict-tag :options="sys_prescription_status" :value="statusForm.status" />
        </el-descriptions-item>
      </el-descriptions>
      <el-form :model="failureForm" style="margin-top: 20px;">
        <el-form-item label="失败原因" prop="failureReason">
          <el-input v-model="failureForm.failureReason" type="textarea" placeholder="请输入处方失败原因" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmSetFailed">确认设置失败</el-button>
        <el-button @click="failureOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Prescription">
import {
  listPrescription,
  getPrescription,
  delPrescription,
  addPrescription,
  updatePrescription,
  remindMedication
} from "@/api/prescription/prescription";
import { listMedication } from "@/api/medication/medication";

const { proxy } = getCurrentInstance();
const { sys_prescription_status } = proxy.useDict("sys_prescription_status");

const prescriptionList = ref([]);
const prescriptionDetailList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedPrescriptionDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeStatus = ref("");
const viewForm = ref({});
const statusOpen = ref(false);
const statusForm = ref({});
const failureOpen = ref(false);
const failureForm = ref({});
const medicationLoading = ref(false);
const medicationOptions = ref([]);
const groupedMedicationOptions = ref([]);
const medicationCache = ref([]);  // 缓存所有药品数据
const categoryOptions = ref([]);
const dosageFormOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    patientsId: null,
    employeeId: null,
    createTime: null,
    status: null,
    money: null,
  },
  rules: {
    patientsId: [
      { required: true, message: "患者id不能为空", trigger: "blur" },
    ],
    employeeId: [
      { required: true, message: "医护人员id不能为空", trigger: "blur" },
    ],
    createTime: [
      { required: true, message: "处方开据时间不能为空", trigger: "blur" },
    ],
    status: [
      {
        required: true,
        message: "状态,1 审核中，2 治疗中，3 已完成，4 已失败不能为空",
        trigger: "change",
      },
    ],
    money: [{ required: true, message: "实收金额不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 状态切换 */
function handleStatusChange(tab) {
  queryParams.value.status = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

/** 查询处方列表 */
function getList() {
  loading.value = true;
  listPrescription(queryParams.value).then(response => {
    if (response.code === 200) {
      prescriptionList.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      proxy.$modal.msgError(response.msg || "获取处方列表失败");
    }
    loading.value = false;
  }).catch(error => {
    proxy.$modal.msgError("获取处方列表失败");
    loading.value = false;
  });
}

/** 每页条数改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

/** 当前页改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientsId: null,
    employeeId: null,
    createTime: null,
    status: null,
    money: null,
  };
  prescriptionDetailList.value = [];
  proxy.resetForm("prescriptionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 新增时先获取药品列表
  getMedicationList();
  open.value = true;
  title.value = "添加处方";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  // 修改时也需要获取药品列表
  getMedicationList();
  const _id = row.id || ids.value;
  getPrescription(_id).then((response) => {
    form.value = response.data;
    prescriptionDetailList.value = response.data.prescriptionDetailList;
    open.value = true;
    title.value = "修改处方";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["prescriptionRef"].validate((valid) => {
    if (valid) {
      // 检查是否存在治疗中的处方
      listPrescription({ patientsId: form.value.patientsId, status: '2' }).then(response => {
        if (response.rows && response.rows.length > 0) {
          proxy.$modal.msgError("该患者已有治疗中的处方，不能新增处方！");
          return;
        }

        // 如果没有治疗中的处方，继续提交
        form.value.prescriptionDetailList = prescriptionDetailList.value;
        addPrescription(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除处方编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPrescription(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 处方明细序号 */
function rowPrescriptionDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 获取药品列表 */
function getMedicationList() {
  medicationLoading.value = true;
  listMedication({
    pageNum: 1,
    pageSize: 100,
    status: '0'
  }).then(response => {
    medicationOptions.value = response.rows;
    // 提取所有不重复的类别和剂型，并转换为中文显示
    const categories = new Set();
    const dosageForms = new Set();

    // 药品类别字典
    const categoryMap = {
      0: '其他',
      1: '抗生素类',
      2: '抗病毒药物',
      3: '抗真菌药物',
      4: '抗肿瘤药物',
      5: '镇痛药物',
      6: '抗抑郁药物'
    };

    // 剂型字典
    const dosageFormMap = {
      0: '其他',
      1: '口服',
      2: '注射',
      3: '外用',
      4: '吸入'
    };

    medicationOptions.value.forEach(item => {
      // 转换类别显示
      const categoryText = categoryMap[item.type] || '其他';
      categories.add(categoryText);
      item.categoryText = categoryText;

      // 转换剂型显示
      const dosageFormText = dosageFormMap[item.dosageForm] || '其他';
      dosageForms.add(dosageFormText);
      item.dosageFormText = dosageFormText;

      // 确保显示正确的信息
      console.log('药品信息:', {
        id: item.id,
        name: item.name,
        type: item.type,
        categoryText: item.categoryText,
        dosageForm: item.dosageForm,
        dosageFormText: item.dosageFormText
      });
    });

    categoryOptions.value = Array.from(categories);
    dosageFormOptions.value = Array.from(dosageForms);

    // 打印分类选项，用于调试
    console.log('可用的药品类别:', categoryOptions.value);
    console.log('可用的剂型:', dosageFormOptions.value);

    medicationLoading.value = false;
  });
}

/** 处理类别变化 */
function handleCategoryChange(value, index) {
  prescriptionDetailList.value[index].categoryFilter = value;
  prescriptionDetailList.value[index].medicationId = undefined;
}

/** 处理剂型变化 */
function handleDosageFormChange(value, index) {
  prescriptionDetailList.value[index].dosageFormFilter = value;
  prescriptionDetailList.value[index].medicationId = undefined;
}

/** 获取过滤后的药品列表 */
function getFilteredMedications(index) {
  const detail = prescriptionDetailList.value[index];
  let filtered = medicationOptions.value;

  if (detail.categoryFilter) {
    filtered = filtered.filter(item => {
      console.log('筛选类别:', {
        filter: detail.categoryFilter,
        itemCategory: item.categoryText,
        match: item.categoryText === detail.categoryFilter
      });
      return item.categoryText === detail.categoryFilter;
    });
  }

  if (detail.dosageFormFilter) {
    filtered = filtered.filter(item => {
      console.log('筛选剂型:', {
        filter: detail.dosageFormFilter,
        itemDosageForm: item.dosageFormText,
        match: item.dosageFormText === detail.dosageFormFilter
      });
      return item.dosageFormText === detail.dosageFormFilter;
    });
  }

  return filtered;
}

/** 处理药品选择变化 */
function handleMedicationChange(value, index) {
  const selectedMedication = medicationOptions.value.find(item => item.id === value);
  if (selectedMedication) {
    prescriptionDetailList.value[index].medicationName = selectedMedication.name;
    prescriptionDetailList.value[index].price = selectedMedication.price;
    prescriptionDetailList.value[index].stockQuantity = selectedMedication.stock;
    prescriptionDetailList.value[index].quantity = 1;
    // 从medication数据中获取用药剂量
    prescriptionDetailList.value[index].dosage = selectedMedication.dosage || '遵医嘱';
    calculateTotal(index);
  }
}

/** 计算总价 */
function calculateTotal(index) {
  const detail = prescriptionDetailList.value[index];
  if (detail.quantity && detail.price) {
    detail.totalAmount = detail.quantity * detail.price;
    // 计算处方总金额
    form.value.money = prescriptionDetailList.value.reduce((sum, item) => {
      return sum + (item.totalAmount || 0);
    }, 0);
  }
}

/** 处方明细添加按钮操作 */
function handleAddPrescriptionDetail() {
  let obj = {
    medicationId: undefined,
    medicationName: '',
    dosage: '',
    quantity: 1,
    price: 0,
    totalAmount: 0,
    categoryFilter: '',
    dosageFormFilter: '',
    stockQuantity: 0
  };
  prescriptionDetailList.value.push(obj);
}

/** 处方明细删除按钮操作 */
function handleDeletePrescriptionDetail() {
  if (checkedPrescriptionDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的处方明细数据");
  } else {
    const prescriptionDetails = prescriptionDetailList.value;
    const checkedPrescriptionDetails = checkedPrescriptionDetail.value;
    prescriptionDetailList.value = prescriptionDetails.filter(function (item) {
      return checkedPrescriptionDetails.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handlePrescriptionDetailSelectionChange(selection) {
  checkedPrescriptionDetail.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "prescription/prescription/export",
    {
      ...queryParams.value,
    },
    `prescription_${new Date().getTime()}.xlsx`
  );
}

/** 查看按钮操作 */
function handleView(row) {
  getPrescription(row.id).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 获取下一状态 */
function getNextStatus(currentStatus) {
  // 审核中 -> 治疗中 -> 已完成
  if (currentStatus === '1') {
    return '2';  // 审核中 -> 治疗中
  } else if (currentStatus === '2') {
    return '3';  // 治疗中 -> 已完成
  }
  return currentStatus;  // 其他状态不变
}

/** 处理状态修改按钮操作 */
function handleStatusUpdate(row) {
  getPrescription(row.id).then(response => {
    statusForm.value = response.data;
    statusOpen.value = true;
  });
}

/** 确认状态修改 */
function confirmStatusChange() {
  const nextStatus = getNextStatus(statusForm.value.status);
  const data = {
    id: statusForm.value.id,
    status: nextStatus
  };

  updatePrescription(data).then(response => {
    proxy.$modal.msgSuccess("状态修改成功");
    statusOpen.value = false;
    getList();
  });
}

/** 设置失败状态 */
function handleSetFailed(row) {
  statusForm.value = row;
  failureOpen.value = true;
}

/** 确认设置失败 */
function confirmSetFailed() {
  const data = {
    id: statusForm.value.id,
    status: 4,
    failureReason: failureForm.value.failureReason
  };

  updatePrescription(data).then(response => {
    proxy.$modal.msgSuccess("状态修改成功");
    failureOpen.value = false;
    failureForm.value.failureReason = '';
    getList();
  });
}

/** 提醒用药按钮操作 */
function handleRemind() {
  const id = ids.value[0];
  proxy.$modal.confirm('是否确认提醒该患者用药？').then(() => {
    return remindMedication(id);
  }).then(() => {
    proxy.$modal.msgSuccess("提醒成功");
  }).catch(() => {});
}

getList();
</script>

<style scoped>
.el-tabs {
  margin-bottom: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.stock-info {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.stock-warning {
  color: #E6A23C;
}

.medication-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  width: 100%;
}

.medication-info {
  display: flex;
  flex-direction: column;
}

.medication-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 3px;
}

.medication-code {
  font-size: 12px;
  color: #909399;
}

.medication-details {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.stock {
  font-size: 13px;
  color: #67C23A;
  margin-bottom: 3px;
}

.low-stock {
  color: #E6A23C;
}

.price {
  font-size: 14px;
  color: #F56C6C;
  font-weight: bold;
}

.medication-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #909399;
  margin-top: 3px;
}

.medication-type,
.medication-category {
  color: #409EFF;
}

.el-select {
  width: 100%;
}
</style>
